<!-- #layout name=default -->
<div id="main" class="fixed" v-cloak>
  <div class="heander-panel">
    <div class="page-header">
      <template v-if="isNewPage">
        <h1 class="title pull-left">{{Kooboo.text.common.Page + ': '}}</h1>
        <div class="form-group pull-left" :class="{'has-error':nameError}">
          <input
            v-kb-tooltip:right.manual.error="nameError"
            type="text"
            placeholder="name"
            class="input-large form-control"
            v-model="name"
            @input="valid"
            @blur="nameInputBlur"
          />
        </div>
      </template>
      <h1 v-else class="title pull-left"
        ><span>{{ Kooboo.text.common.Page + ': '}}</span
        ><strong :title="name">{{name}}</strong></h1
      >
      <kb-multilang-selector
        v-if="multiLangs"
        v-show="curType == 'preview'"
        :cultures="multiLangs.cultures"
        :default-culture="multiLangs.default"
      ></kb-multilang-selector>
      <button
        v-show="pageContent && curType == 'code'"
        @click="formatCode"
        type="button"
        class="btn btn-default pull-right"
        >Format code</button
      >
    </div>
  </div>
  <div class="block-fullpage with-buttons">
    <div class="block-visual-editor default">
      <div class="tabs-bottom">
        <div class="tab-content">
          <section class="tab-pane" :class="{ 'active': curType == 'preview' }">
            <div class="kb-editor">
              <iframe
                src="about:blank"
                id="page_iframe"
                class="kb-iframe"
              ></iframe>
            </div>
            <div class="kb-panel">
              <ul class="nav nav-tabs">
                <li class="active">
                  <a href="#page_setting" data-toggle="tab">Settings</a>
                </li>
              </ul>
              <div class="tab-content">
                <section class="active" id="page_setting" class="tab-pane">
                  <div class="panel-group">
                    <kb-page-basic-settings
                      v-if="settings&&multiLangs"
                      :settings="settings"
                      :multi-langs="multiLangs"
                    >
                    </kb-page-basic-settings>
                    <kb-page-html-meta
                      v-if="settings&&multiLangs"
                      :settings="settings"
                      :default-lang="multiLangs.default"
                    >
                    </kb-page-html-meta>

                    <kb-page-parameters
                      v-if="settings"
                      :parameters="settings.parameters"
                    >
                    </kb-page-parameters>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Styles"
                        >
                          <h4 class="panel-title">Styles</h4>
                        </div>
                        <div
                          id="J_Setting_Styles"
                          class="panel-collapse collapse"
                        >
                          <ul
                            class="list-group"
                            v-kb-sortable="bindingPanel.styleList"
                            @after-sort="bindingPanel.styleSorted"
                          >
                            <template
                              v-for="(item,index) in bindingPanel.styleList"
                            >
                              <li :key="index" class="list-group-item">
                                <span class="sortable"
                                  ><i class="glyphicon glyphicon-list"></i
                                ></span>
                                <a
                                  class="btn gray btn-xs pull-right margin-right-5"
                                  href="javascript:;"
                                  title="Remove"
                                  v-kb-tooltip:top="Kooboo.text.common.remove"
                                  @click="removeStyle(item)"
                                  ><i class="fa fa-minus"></i
                                ></a>
                                <a
                                  v-if="item.text"
                                  class="btn blue btn-xs pull-right"
                                  href="javascript:;"
                                  title="Edit"
                                  v-kb-tooltip:top="Kooboo.text.common.edit"
                                  @click="editJsCss(item)"
                                  ><i class="fa fa-pencil"></i
                                ></a>
                                <span class="nowrap-text">{{item.name}}</span>
                              </li>
                            </template>
                          </ul>
                          <div class="panel-body">
                            <button
                              type="button"
                              class="btn blue btn-xs pull-right"
                              @click="createStyle"
                              ><i class="fa fa-plus"></i
                            ></button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Scripts"
                        >
                          <h4 class="panel-title">Scripts</h4>
                        </div>
                        <div
                          id="J_Setting_Scripts"
                          class="panel-collapse collapse"
                        >
                          <div class="panel-body">
                            <strong>Head</strong>
                          </div>
                          <ul
                            class="list-group"
                            id="head-scripts"
                            v-kb-sortable="bindingPanel.headScriptList"
                            @after-sort="bindingPanel.headScriptSorted"
                            style="min-height: 40px;"
                            data-sort-connect="#body-scripts"
                          >
                            <template
                              v-for="(item,index) in bindingPanel.headScriptList"
                            >
                              <li class="list-group-item" :key="index">
                                <span class="sortable"
                                  ><i class="glyphicon glyphicon-list"></i
                                ></span>
                                <a
                                  class="btn gray btn-xs pull-right margin-right-5"
                                  href="javascript:;"
                                  title="Remove"
                                  v-kb-tooltip:top="Kooboo.text.common.remove"
                                  @click="removeScript(item)"
                                  ><i class="fa fa-minus"></i
                                ></a>
                                <a
                                  v-if="item.text"
                                  class="btn blue btn-xs pull-right"
                                  href="javascript:;"
                                  title="Edit"
                                  v-kb-tooltip:top="Kooboo.text.common.edit"
                                  @click="editJsCss(item)"
                                  ><i class="fa fa-pencil"></i
                                ></a>
                                <span class="nowrap-text">{{item.name}}</span>
                              </li>
                            </template>
                          </ul>
                          <div class="panel-body">
                            <button
                              type="button"
                              class="btn blue btn-xs pull-right"
                              @click="createScript(true)"
                              ><i class="fa fa-plus"></i
                            ></button>
                          </div>
                          <div class="panel-body">
                            <strong>Body</strong>
                          </div>
                          <ul
                            class="list-group"
                            id="body-scripts"
                            v-kb-sortable="bindingPanel.bodyScriptList"
                            @after-sort="bindingPanel.bodyScriptSorted"
                            data-sort-connect="#head-scripts"
                            style="min-height: 40px;"
                          >
                            <template
                              v-for="(item,index) in bindingPanel.bodyScriptList"
                            >
                              <li class="list-group-item" :key="index">
                                <span class="sortable"
                                  ><i class="glyphicon glyphicon-list"></i
                                ></span>
                                <a
                                  class="btn gray btn-xs pull-right margin-right-5"
                                  href="javascript:;"
                                  title="Remove"
                                  v-kb-tooltip:top="Kooboo.text.common.remove"
                                  @click="removeScript(item)"
                                  ><i class="fa fa-minus"></i
                                ></a>
                                <a
                                  v-if="item.text"
                                  class="btn blue btn-xs pull-right"
                                  href="javascript:;"
                                  title="Edit"
                                  v-kb-tooltip:top="Kooboo.text.common.edit"
                                  @click="editJsCss(item)"
                                  ><i class="fa fa-pencil"></i
                                ></a>
                                <span class="nowrap-text">{{item.name}}</span>
                              </li>
                            </template>
                          </ul>
                          <div class="panel-body">
                            <button
                              type="button"
                              class="btn blue btn-xs pull-right"
                              @click="createScript(false)"
                              ><i class="fa fa-plus"></i
                            ></button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div class="panel panel-default">
                        <div
                          class="panel-heading clickable"
                          data-toggle="collapse"
                          data-target="#J_Setting_Cache"
                        >
                          <h4 class="panel-title">Cache</h4>
                        </div>
                        <div
                          id="J_Setting_Cache"
                          class="panel-collapse collapse"
                        >
                          <div class="panel-body">
                            <div style="display: flex;align-items: center;margin: 8px 0;">
                              <label class="control-label"><span>Enable cache</span></label>
                              <div style="flex: 1;"></div>
                              <kb-switch v-model="enableCache"></kb-switch>
                            </div>
                            <div style="display: flex;align-items: center;margin: 8px 0;" v-if="enableCache">
                              <label class="control-label"><span>Cache by version</span></label>
                              <div style="flex: 1;"></div>
                              <kb-switch v-model="cacheByVersion" ></kb-switch>
                            </div>
                            <div v-if="enableCache&&!cacheByVersion">
                              <span style="display: block;padding: 5px;">Time</span>
                              <div class="input-group" >
                                <input class="form-control" type="number" v-model="cacheMinutes" />
                                <div  class="input-group-addon">Minutes</div>
                              </div>
                            </div>
                            <div v-if="enableCache">
                              <span style="display: block;padding: 5px;">Cache query keys</span>
                              <input class="form-control"  v-model="cacheQueryKeys" placeholder='Example: category,page,index' />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </section>
              </div>
            </div>
          </section>
          <section class="tab-pane" :class="{active: curType == 'code'}">
            <kb-code-editor
              :code.sync="pageContent"
              auto-size
              lang="html"
              ref="codeEditor"
            ></kb-code-editor>
          </section>
        </div>
        <ul class="nav nav-tabs">
          <li
            :class="{active: curType == 'preview'}"
            @click="changeType('preview')"
          >
            <a href="javascript:;">Preview</a>
          </li>
          <li :class="{active: curType == 'code'}" @click="changeType('code')">
            <a href="javascript:;">Source code</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <div class="page-buttons">
    <div class="btn-group dropup">
      <button class="btn green" style="margin: 0;" @click="onSaveAndReturn"
        >Save &amp; Return</button
      >
      <a
        class="btn green dropdown-toggle"
        data-toggle="dropdown"
        style="margin:0;min-width:auto;"
      >
        <i class="fa fa-angle-up"></i>
      </a>
      <ul class="dropdown-menu" role="menu">
        <li><a href="javascript:;" @click="onSave">Save</a></li>
      </ul>
    </div>
    <a href="javascript:;" @click="userCancel" class="btn gray">Cancel</a>
  </div>
  <kb-page-widget-meta
    v-if="multiLangs"
    :multi-langs="multiLangs"
  ></kb-page-widget-meta>
  <kb-layout-style-script></kb-layout-style-script>
</div>

<script>
  Kooboo.pageEditor = {
    component: {},
    store: {},
    util: {},
    viewModel: {},
    widget: {}
  };
  window.__pageEditor = {};
</script>
<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kb-code-editor.js",
      "/_Admin/Scripts/kooboo/Guid.js",
      "/_Admin/Scripts/lib/jquery-ui-customized.js",
      "/_Admin/Scripts/lib/jquery.textarea_autosize.min.js",
      "/_Admin/Scripts/lib/bootstrap3-typeahead.min.js",
      "/_Admin/Scripts/components/kbTypeahead.js",
      "/_Admin/Scripts/lib/x-editable/bootstrap-editable.min.js",
      "/_Admin/Scripts/components/kbMultilangSelector.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Position.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Label.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Script.js",
      "/_Admin/Scripts/layoutEditor/viewModel/Style.js",
      "/_Admin/Scripts/pageEditor/stores/ComponentStore.js",
      "/_Admin/Scripts/layoutEditor/stores/PositionStore.js",
      "/_Admin/Scripts/layoutEditor/stores/BindingStore.js",
      "/_Admin/Scripts/layoutEditor/viewModel/BindingPanel.js",
      "/_Admin/Scripts/pageEditor/components/basic-settings.js",
      "/_Admin/Scripts/pageEditor/components/htmlmeta.js",
      "/_Admin/Scripts/pageEditor/components/parameters.js",
      "/_Admin/Scripts/pageEditor/widgets/html-meta.js",
      "/_Admin/Scripts/layoutEditor/components/style-script.js",
      "/_Admin/Scripts/layoutEditor/components/KBFrame.js",
      "/_Admin/Scripts/lib/js-beautify/lib/beautify-html.js",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.js",
      "/_Admin/Scripts/components/kbSwitch.js"
    ]);
    Kooboo.loadCSS([
      "/_Admin/Styles/bootstrap-editable/css/bootstrap-editable.css",
      "/_Admin/Scripts/lib/bootstrap-switch/bootstrap-switch.min.css"
    ]);
  })();

  (function() {
    var Guid = Kooboo.Guid,
      BindingStore = Kooboo.pageEditor.store.BindingStore,
      BindingPanel = Kooboo.pageEditor.viewModel.BindingPanel,
      KBFrame = Kooboo.pageEditor.component.KBFrame;

    var self = new Vue({
      el: "#main",
      data: function() {
        return {
          isNewPage: false,
          pageId: Kooboo.getQueryString("Id") || Guid.Empty,
          name: "",
          nameError: "",
          posted: false,
          bindingPanel: new BindingPanel(),
          multiLangs: null,
          pageContent: "",
          backupPageContent: "",
          kbFrame: null,
          curType: "preview",
          settings: null,
          isTitleChanged: false,
          isMetaChanged: false,
          isUrlChanged: false,
          isBodyChanged: false,
          isSaveAndReturn: false,
          enableCache:false,
          cacheByVersion:false,
          cacheMinutes:3,
          cacheQueryKeys:""
        };
      },
      computed: {
        isContentChanged: function() {
          var self = this;
          return (
            self.isTitleChanged ||
            self.isMetaChanged ||
            self.isUrlChanged ||
            self.isBodyChanged ||
            (self.curType == "code"
              ? self.pageContent !== self.backupPageContent
              : false)
          );
        }
      },
      mounted: function() {
        var self = this;
        self.isNewPage = self.pageId == Guid.Empty;
        self.kbFrame = new KBFrame(document.getElementById("page_iframe"), {
          type: "normal_page"
        });
        window.__pageEditor.kbFrame = self.kbFrame;
        $.when(
          Kooboo.Page.getEdit({
            Id: self.pageId
          }),
          Kooboo.Site.Langs(),
          Kooboo.Style.getExternalList(),
          Kooboo.Script.getExternalList(),
          Kooboo.ResourceGroup.Style(),
          Kooboo.ResourceGroup.Script()
        ).then(function(page, langs, styles, scripts, styleGroup, scriptGroup) {
          var styleList = [],
            styleGroupList = [],
            scriptList = [],
            scriptGroupList = [];

          page = $.isArray(page) ? page[0] : page;
          styles = $.isArray(styles) ? styles[0] : styles;
          scripts = $.isArray(scripts) ? scripts[0] : scripts;
          styleGroup = $.isArray(styleGroup) ? styleGroup[0] : styleGroup;
          scriptGroup = $.isArray(scriptGroup) ? scriptGroup[0] : scriptGroup;

          styles.model.forEach(function(style) {
            styleList.push({
              id: style.id,
              text: style.name,
              url: style.routeName
            });
          });

          scripts.model.forEach(function(script) {
            scriptList.push({
              id: script.id,
              text: script.name,
              url: script.routeName
            });
          });

          styleGroup.model.forEach(function(style) {
            styleGroupList.push({
              id: style.id,
              text: style.name,
              url: style.relativeUrl
            });
          });

          scriptGroup.model.forEach(function(script) {
            scriptGroupList.push({
              id: script.id,
              text: script.name,
              url: script.relativeUrl
            });
          });

          self.bindingPanel.styleResource = {
            styles: styleList,
            styleGroup: styleGroupList
          };

          self.bindingPanel.scriptResource = {
            scripts: scriptList,
            scriptGroup: scriptGroupList
          };
          self.enableCache=page.model.enableCache;
          self.cacheByVersion=page.model.cacheByVersion;
          self.cacheMinutes=page.model.cacheMinutes||3;
          self.cacheQueryKeys=page.model.cacheQueryKeys||"";
          self.multiLangs = langs[0].model;
          self.pageContent = page.model.body || "";
          self.setHTML(self.pageContent, function() {
            self.name = page.model.name;
            self.settings = page.model;
          });
        });

        Kooboo.EventBus.subscribe("kb/page/field/change", function(data) {
          switch (data.type) {
            case "title":
              self.isTitleChanged = true;
              break;
            case "meta":
              self.isMetaChanged = true;
              break;
            case "url":
              self.isUrlChanged = true;
              break;
            case "resource":
              self.isBodyChanged = true;
              break;
          }
        });

        Kooboo.EventBus.subscribe("kb/page/final/save", function(res) {
          if (!res.errorCount || res.errorCount == 0) {
            res["body"] =
              self.curType == "preview"
                ? self.kbFrame.getHTML()
                : self.pageContent;
            res["name"] = self.name;
            res["id"] = self.pageId;
            res["enableCache"] = self.enableCache;
            res["cacheByVersion"] = self.cacheByVersion;
            res["cacheMinutes"] = self.cacheMinutes;
            res["cacheQueryKeys"] = self.cacheQueryKeys;
            self.submitData = res;

            if (self.isSaveAndReturn) {
              self.onSubmit(function() {
                self.goBack();
              });
            } else {
              self.onSubmit(function(id) {
                if (self.isNewPage) {
                  location.href = Kooboo.Route.Get(Kooboo.Route.Page.EditPage, {
                    id: id
                  });
                } else {
                  self.isTitleChanged = false;
                  self.isMetaChanged = false;
                  self.isUrlChanged = false;
                  self.isBodyChanged = false;
                  self.nameError = "";
                  window.info.show(Kooboo.text.info.save.success, true);
                }
              });
            }
          }
        });

        Kooboo.EventBus.subscribe("binding/remove", function(data) {
          var item = BindingStore.byId(data.id);

          if (item) {
            BindingStore.remove(data.id);
          }
        });
      },
      methods: {
        onSaveAndReturn: function() {
          self.isSaveAndReturn = true;
          if (self.curType == "code") {
            self.setHTML(self.pageContent, function() {
              Kooboo.EventBus.publish(
                "kb/page/title/set",
                self.kbFrame.getTitle()
              );
              setTimeout(function() {
                Kooboo.EventBus.publish("kb/page/save", {});
              }, 250);
            });
          } else {
            Kooboo.EventBus.publish("kb/page/save", {});
          }
        },
        onSave: function() {
          self.isSaveAndReturn = false;
          if (self.curType == "code") {
            self.setHTML(self.pageContent, function() {
              Kooboo.EventBus.publish(
                "kb/page/title/set",
                self.kbFrame.getTitle()
              );
              setTimeout(function() {
                Kooboo.EventBus.publish("kb/page/save", {});
              }, 250);
            });
          } else {
            Kooboo.EventBus.publish("kb/page/save", {});
          }
        },
        valid: function(isPosted) {
          if (!self.posted || !self.isNewPage) return true;
          var rules = [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            }
          ];
          if (isPosted) {
            rules.push({
              remote: {
                url: Kooboo.Page.isUniqueName(),
                data: function() {
                  return {
                    name: self.name
                  };
                }
              },
              message: Kooboo.text.validation.taken
            });
          }

          var result = Kooboo.validField(self.name, rules);
          self.nameError = result.msg;
          return result.valid;
        },
        goBack: function() {
          location.href = Kooboo.Route.Get(Kooboo.Route.Page.ListPage);
        },
        onSubmit: function(cb) {
          function submit() {
            Kooboo.Page.post(JSON.stringify(self.submitData)).then(function(
              res
            ) {
              if (res.success) {
                if (typeof cb == "function") {
                  cb(res.model);
                }
              }
            });
          }
          self.posted = true;
          if (self.valid(true)) {
            submit();
          }
        },
        setHTML: function(html, callback) {
          BindingStore.clear();

          !self.kbFrame.hasResource() &&
            self.kbFrame.setResource(self.bindingPanel.resources);

          self.kbFrame.setContent(html, function() {
            self.bindingPanel.elem = self.kbFrame.getDocumentElement();
            if (callback) callback();
          });
        },
        userCancel: function() {
          if (self.isContentChanged) {
            if (confirm(Kooboo.text.confirm.beforeReturn)) {
              self.goBack();
            }
          } else {
            self.goBack();
          }
        },
        changeType: function(type) {
          if (self.curType !== type) {
            if (type == "code") {
              self.pageContent = html_beautify(self.kbFrame.getHTML());
              self.backupPageContent = self.pageContent;
            } else {
              if (self.backupPageContent != self.pageContent) {
                self.setHTML(self.pageContent, function() {
                  Kooboo.EventBus.publish(
                    "kb/page/title/set",
                    self.kbFrame.getTitle()
                  );
                });
              }
            }
            self.curType = type;
          }
        },
        formatCode: function(cb) {
          self.$refs.codeEditor.formatCode(cb);
        },
        removeStyle: function(item) {
          self.bindingPanel.removeStyle(item);
        },
        editJsCss: function(item) {
          self.bindingPanel.editJsCss(item);
        },
        removeScript: function(item) {
          self.bindingPanel.removeScript(item);
        },
        createStyle: function() {
          self.bindingPanel.createStyle();
        },
        createScript: function(b) {
          self.bindingPanel.createScript(b);
        },
        nameInputBlur: function() {
          if (!self.name) return;
          Kooboo.EventBus.publish("kb/page/url/route/set", self.name);
        }
      }
    });
  })();
</script>
